package org.example.netty.demo.chapter4;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * @author ： minzhiwei
 * create by 2020/1/19 16:07
 * @description
 */
public class HttpServer {
    public static void main(String[] args) throws InterruptedException {
        final NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(eventExecutors, eventExecutors)
                .channel(NioServerSocketChannel.class)
                .localAddress(9999)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        KeyStore ks = KeyStore.getInstance("JKS"); /// "JKS"  　　　　  　　
                        InputStream ksInputStream = new FileInputStream("D:\\key\\shfqkeystore.jks"); /// 证书存放地址
                        String password = "123456";
                        ks.load(ksInputStream, password.toCharArray());
                        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(ks, password.toCharArray());
                        SSLContext sslContext = SSLContext.getInstance("TLS");
                        sslContext.init(kmf.getKeyManagers(), null, null);
                        ChannelPipeline pipeline = ch.pipeline();
                        final SSLEngine sslEngine = sslContext.createSSLEngine();
                        sslEngine.setUseClientMode(false);
                        sslEngine.setNeedClientAuth(false);
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                        pipeline.addLast("decoder", new HttpRequestDecoder());
                        pipeline.addLast("encoder", new HttpResponseEncoder());
                        pipeline.addLast("handler", new HttpHandler());
                    }
                });
        final ChannelFuture sync = serverBootstrap.bind().sync();
        sync.channel().closeFuture().sync();
        eventExecutors.shutdownGracefully();
    }
}
